package com.trz.cqrs.core.priority;



import com.trz.cqrs.es.event.priority.Priority;
import com.trz.cqrs.es.event.priority.Strategy;
import org.springframework.stereotype.Component;
import com.trz.cqrs.core.entity.EventEntity;

import static java.lang.Math.abs;
import static java.lang.Math.min;

@Component
public class GradientDescentStrategy implements PriorityStrategy {

    @Override
    public Strategy getStrategy() {
        return Strategy.GRADIENT_DESCENT;
    }

    @Override
    public void adjust(EventEntity entity) {
        /*
         * f(c, p) = min(*, 8)
         * case c = 0
         *      * = p or 4 * (p % 9)
         * case p in [0, 9)
         *      * = p + (c % 500 == 0 ? 1 : 0)
         * case p in [9, 12)
         *      * = 4 * (p % 9) + (c % 500 == 0 ? 1 : 0)
         */
//        val c = entity.getCount();
//        val p = entity.getPriority().ordinal();
//        Priority.values();

//        entity.setPriority(Priority.values()[min((p / 9 * 3 + 1) * (p % 9) + (c > 0 ? abs(c % 500 - 1 >> 31) : 0), 8)]);
        //p1-p8每个执行一次 p9执行一直执行
        Priority priority = Priority.P9;
        if(entity.getPriority().ordinal()<Priority.values().length-1){
            priority = Priority.values()[entity.getPriority().ordinal()+1];
        }
        entity.setPriority(priority);

    }

}
